package com.abbas.CayTcore.base

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding

/**
 * fragment基类
 * MVP架构
 * 由于使用了Navigation，创建的fragment不走destroy，但是依旧走onCreate
 * 为了统一生命周期，fragment的view、P层、binding生命周期相同
 */
abstract class BaseFragment<V : BaseView, P : BasePresenter<V, *>, VB : ViewBinding> : Fragment(),
    BaseView {

    protected var rootView: View? = null
    protected lateinit var presenter: P
    private var _binding: VB? = null
    protected val binding get() = _binding!!

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.e("Tag", "onCreate::::$this::::${hashCode()}")
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        Log.e("Tag", "onCreateView")

        _binding = getViewBinding(inflater, container, savedInstanceState)
        rootView = binding.root

        presenter = initPresenter()
        presenter.let {
            it.attach(this)
            lifecycle.addObserver(it)
        }

        initData()
        initEvent()
        return rootView
    }

    abstract fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): VB

    abstract fun initPresenter(): P

    abstract fun initData()

    abstract fun initEvent()

    override fun onDestroyView() {
        super.onDestroyView()
        rootView = null
        _binding = null
        Log.e("Tag", "onDestroyView::::$this::::${hashCode()}")
    }
}